//
//  MqInfoWebViewController.m
//  Meiqi
//
//  Created by 王郑 on 16/1/14.
//  Copyright © 2016年 KFC. All rights reserved.
//

#import "MqInfoWebViewController.h"
#import "MqTagModel.h"
#import "MqAuthModel.h"
#import "MqInfoListModel.h"
#import "MqCommentModel.h"
#import "MqTInfoCommentableViewCell.h"
#import "MqInfoTagTableViewCell.h"
#import "MqInfoAuthTableViewCell.h"
#import "MqInfoMoreViewController.h"
#import "MqInfoAuthDetailViewController.h"
#import "MqMyCollectionModel.h"
@interface MqInfoWebViewController ()<UIWebViewDelegate,UITableViewDelegate,UITableViewDataSource>

// webview
@property (strong, nonatomic) UIWebView *webView;

// 总的tableView
@property (strong, nonatomic) UITableView *mainTableView;
// 自定义的表头 : 标题栏 + webView
@property (strong, nonatomic) UIView *headView;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UILabel *timeLabel;
@property (strong, nonatomic) UILabel *authLabel;
@property (strong, nonatomic) UILabel *clickLabel;
@property (nonatomic, strong) UIView *barView;

// webView的高度
@property (assign, nonatomic) CGFloat height;

// 标签数据源
@property (strong, nonatomic) NSMutableArray *tagListArray;
// 作者数据源
@property (strong, nonatomic) NSMutableArray *authArray;
// 推荐文章数据源
@property (strong, nonatomic) NSMutableArray *recommendListArray;
// 评论的数据源
@property (strong, nonatomic) NSMutableArray *commentListArray;

// 分区栏名字
@property (strong, nonatomic) NSArray *sectionNameArray;


@property (strong, nonatomic) NSMutableArray *UrlArray;


@property (nonatomic, strong) NSDictionary *detailsDic;

@end

@implementation MqInfoWebViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];

    
#pragma maek ----- 数据源数组
    _tagListArray = [NSMutableArray array];
    _authArray = [NSMutableArray array];
    _recommendListArray = [NSMutableArray array];
    _commentListArray =[NSMutableArray array];
    
    _UrlArray = [NSMutableArray array];
    
    // 给区头名字赋值
    _sectionNameArray = @[@"",@"",@"",@""];
#pragma maek ----- 自定义导航栏
    [self addNavBar];
    
#pragma mark ---- 添加tableview
    [self addTableview];
    [self.view bringSubviewToFront:_barView];
}


#pragma mark ---- 收藏
- (void)collectionArticle{
    
    MqMyCollectionModel *model = [[MqMyCollectionModel alloc] init];
   model.account = [[NSUserDefaults standardUserDefaults] objectForKey:@"account"];
    if (!model.account) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
        [alert show];
        
        //  提示两秒后关闭
        [self performSelector:@selector(closeMessage:) withObject:alert afterDelay:1];
        
        return;
        
    }
    
    model.smalltext = _detailsDic[@"smalltext"];
    model.title = _detailsDic[@"title"];
    model.newstime = _detailsDic[@"newstime"];
    
    
    // 建表
    [[MqDatabase dataBaseHandle] buildListWithString:@"CREATE TABLE IF NOT EXISTS collection (account text, smalltext text, title text, newstime text, idsURL text,authorInfoURL text,tagListURL text,recommendListURL text, commentURL text)"];
    
    FMResultSet *result = [[MqDatabase dataBaseHandle].db executeQuery:[NSString stringWithFormat:@"SELECT smalltext FROM collection where account = %@",model.account]];
    while ([result next]) {
        
        //  取出数据库中每一行字段的值
        NSString *smalltext = [result stringForColumn:@"smalltext"];
        
        if ([smalltext isEqualToString:model.smalltext]) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏过" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
            [alert show];
            
            //  提示两秒后关闭
            [self performSelector:@selector(closeMessage:) withObject:alert afterDelay:1];
            
            return;
            
        }
    }
    
    
    NSString *insertString = [NSString stringWithFormat:@"INSERT INTO collection (account, smalltext, title, newstime, idsURL,authorInfoURL,tagListURL,recommendListURL,commentURL) VALUES(?, ?, ?, ?, ?,?,?,?,?)"];
    
    
    [[MqDatabase dataBaseHandle].db executeUpdate:insertString,model.account, model.smalltext,model.title,model.newstime,_idsURL,_authorInfoURL,_tagListURL,_recommendListURL,_commentURL];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alert show];
    
    //  提示两秒后关闭
    [self performSelector:@selector(closeMessage:) withObject:alert afterDelay:1];
    
}


- (void)closeMessage:(UIAlertView *)alert{
    
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)morePushNoti:(NSNotification *)noti
{
    
    NSDictionary *dic = noti.userInfo;
    NSString *url = dic[@"url"];
    NSString *title = dic[@"title"];
    MqInfoMoreViewController *moreVC = [[MqInfoMoreViewController alloc] init];
    moreVC.moreURL = url;
    moreVC.titleString = title;
    [self.navigationController pushViewController:moreVC animated:YES];
    
    //[[NSNotificationCenter defaultCenter]removeObserver:self name:@"morePush" object:nil];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    // 添加tag上按钮的通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(morePushNoti:) name:@"morePush" object:nil];

}

- (void)viewWillDisappear:(BOOL)animated
{
     [[NSNotificationCenter defaultCenter]removeObserver:self name:@"morePush" object:nil];
    
}

#pragma mark ----  获取数据
- (void)setUpData1
{
#pragma mark ----  获取标签
    [PKRequestManager requestWithUrlString:_tagListURL parDic:nil Method:GET finish:^(NSData *data) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        NSArray *tagList = dic[@"tagList"];
        
        for (NSDictionary *oneDic in tagList) {
            
            MqTagModel *model = [[MqTagModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_tagListArray addObject:model];
        }
        
          [_mainTableView reloadData];
        
    } error:^(NSError *error) {

        
    } path:@"tagListData"];
    
}

- (void)setUpData2
{
    
#pragma mark ----  获取作者信息
    [PKRequestManager requestWithUrlString:_authorInfoURL parDic:nil Method:GET finish:^(NSData *data) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        NSArray *authorList = dic[@"authorList"];
        for (NSDictionary *oneDic in authorList) {
            
            MqAuthModel *model = [[MqAuthModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_authArray addObject:model];
            
        }
        
        [_mainTableView reloadData];
        
    } error:^(NSError *error) {
        
    } path:@"authData"];
    
}

- (void)setUpData3
{
#pragma mark ----  获取相关推荐信息
    [PKRequestManager requestWithUrlString:_recommendListURL parDic:nil Method:GET finish:^(NSData *data) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        if (!dic[@"list"] ) {
            
            NSArray *list = dic[@"list"];
            
            for (NSDictionary *oneDic in list) {
                
                MqInfoListModel *model = [[MqInfoListModel alloc] init];
                [model setValuesForKeysWithDictionary:oneDic];
                [_recommendListArray addObject:model];
                
            }
        }
    
        [_mainTableView reloadData];
        
    } error:^(NSError *error) {
//        NSLog(@"%@",error);
        
    } path:@"recommendData"];

}

- (void)setUpData4
{
#pragma mark ----  获取评论信息
    [PKRequestManager requestWithUrlString:_commentURL parDic:nil Method:GET finish:^(NSData *data) {
        
        NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        for (NSDictionary *oneDic in array) {
            
            MqCommentModel *model = [[MqCommentModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [_commentListArray addObject:model];
            
        }
        
        [_mainTableView reloadData];
        
    } error:^(NSError *error) {
        
    } path:@"commentData"];
    
    
}
#pragma mark ---- 展示详情的tableView
- (void)addTableview
{
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth,70 + kScreenHeight - (64 + 49) * kHeightBase) style:(UITableViewStylePlain)];
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    
#pragma mark ---- 先添加表头
    [self addHeadView];
    
    [self.view addSubview:_mainTableView];

}


- (void)addHeadView
{
    
    _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight )];
    
    // 添加标题栏
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * kWidthBase, 10* kHeightBase, kScreenWidth - 20 * kWidthBase, 60 * kHeightBase)];
    _titleLabel.font = [UIFont systemFontOfSize:22];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.numberOfLines = 0;
    [_headView addSubview:_titleLabel];
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(_titleLabel.left, _titleLabel.bottom + 10 * kHeightBase, 5 * kWidthBase, 20 * kHeightBase)];
    line.backgroundColor = [UIColor redColor];
    [_headView addSubview:line];
    
    _authLabel = [[UILabel alloc] initWithFrame:CGRectMake(line.right + 2 * kWidthBase, line.top, 150 * kWidthBase, line.height)];
    _authLabel.textColor = [UIColor grayColor];
    _authLabel.font = [UIFont systemFontOfSize:13];
    [_headView addSubview:_authLabel];
    
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(_authLabel.right + 5 * kWidthBase, _authLabel.top, 60 * kWidthBase, line.height)];
    _timeLabel.textColor = [UIColor grayColor];
    _timeLabel.font = [UIFont systemFontOfSize:13];
    [_headView addSubview:_timeLabel];
    
    _clickLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 100 * kWidthBase, _timeLabel.top, 80 * kWidthBase, line.height)];
    _clickLabel.font = [UIFont systemFontOfSize:13];
    _clickLabel.textColor = [UIColor grayColor];
    _clickLabel.textAlignment = NSTextAlignmentRight;
    [_headView addSubview:_clickLabel];
    
    UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(0, line.bottom + 10 * kHeightBase, kScreenWidth, 1)];
    line2.backgroundColor = [UIColor grayColor];
    [_headView addSubview:line2];
    
#pragma maek ----- 添加webView
    [self addWebView];
    
#pragma maek ----- 解析网页的数据
    [self setUpWebData];
    
    
}
#pragma mark ---- 第二个网页样式 : 进行了拼接
- (void)addWebView
{
    
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 120 * kHeightBase, kScreenWidth, _headView.height - 120 * kHeightBase)];
    _webView.scrollView.scrollEnabled = NO;
    _webView.delegate = self;
    // 把网页添加到表头上:
    [_webView sizeToFit];
    [_headView addSubview:_webView];
    
}
#pragma mark ---- 实现解析网页的数据
- (void)setUpWebData
{
    
    [PKRequestManager requestWithUrlString:_idsURL parDic:nil Method:GET finish:^(NSData *data) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        _detailsDic = dic[@"details"];
//        NSLog(@"%@",detailsDic);
        // 给表头上的控件赋值
//        _titleLabel.text = detailsDic[@"title"];
        _authLabel.text = [NSString stringWithFormat:@"作者:%@",_detailsDic[@"writer"]];
        _timeLabel.text = _detailsDic[@"newstime"];
        _clickLabel.text = [NSString stringWithFormat:@"%@ 点击",_detailsDic[@"onclick"]];
        
        NSString *webStr = _detailsDic[@"newstext"];
        webStr = [webStr stringByReplacingOccurrencesOfString:@"img src=\"" withString:@"img src=\"http://www.biketo.com"];
        // 修改图片 和 视频 的大小
        webStr = [NSString stringWithFormat:@"<head><style>img{width:%fpx !important;}</style></head>%@",kScreenWidth - 15*kWidthBase,webStr];
        webStr = [NSString stringWithFormat:@"<head><style>iframe{width:%fpx !important;}</style></head>%@",kScreenWidth - 30*kWidthBase,webStr];
        //设置内容，这里包装一层div，用来获取内容实际高度（像素）
        NSString * htmlcontent = [NSString stringWithFormat:@"<div id=\"webview_content_wrapper\">%@</div>", webStr];
        
        [_webView loadHTMLString:htmlcontent baseURL:nil];
        
        
        
    } error:^(NSError *error) {
        
//        NSLog(@"%@",error);
        
    } path:@"webData"];
    
}
#pragma mark ---- 加载完网页后做的操作
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    // 修改headView的frame
#pragma mark ---- 自适应WebView的高度
    float clientheight = [[_webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
    // 设置到WebView上
    _webView.frame = CGRectMake(0, 120 * kHeightBase, kScreenWidth, clientheight);
    // 获取WebView最佳尺寸（点）
    CGSize frame = [_webView sizeThatFits:_webView.frame.size];
    // 获取内容实际高度（像素）
    NSString * height_str= [webView stringByEvaluatingJavaScriptFromString: @"document.getElementById('webview_content_wrapper').offsetHeight + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-top'))  + parseInt(window.getComputedStyle(document.getElementsByTagName('body')[0]).getPropertyValue('margin-bottom'))"];
    float trueHeight = [height_str floatValue];
    
    //内容实际高度（像素）* 点和像素的比
    trueHeight = trueHeight * frame.height / clientheight;
    //再次设置WebView高度（点）
    _height = trueHeight;
    
    // 修改webView的高度
    _webView.frame = CGRectMake(0, 120 * kHeightBase, kScreenWidth, _height);
    
    // 然后修改headView的高度
    _headView.frame = CGRectMake(0, 0, kScreenWidth, 120 * kHeightBase + _height);
    
    _mainTableView.tableHeaderView = _headView;
    
    
#pragma mark ----  获取数据
    [self setUpData1];
    [self setUpData2];
    [self setUpData3];
    [self setUpData4];
    
    // 重新给区头名字赋值
    _sectionNameArray = @[@"标签",@"作者",@"相关文章",@"最新评论"];
 
    
    //这里是js，主要目的实现对图片url的获取
    
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.getElementsByTagName(\"img\");\
    var imgScr = '';\
    for(var i=0;i<objs.length;i++){\
    imgScr = imgScr + objs[i].src + '+';\
    };\
    return imgScr;\
    };";
    
    //注入js方法
    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];
    
    // 联合图片url
    NSString *urlResurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    _UrlArray = [NSMutableArray arrayWithArray:[urlResurlt componentsSeparatedByString:@"+"]];
    
    //  比实际多一张
    if (_UrlArray.count >= 2) {
        [_UrlArray removeLastObject];
    }
    
   //urlResurlt 就是获取到得所有图片的url的拼接；mUrlArray就是所有Url的数组
    
                                             
    //  添加图片可点击的js
 
    //  添加图片可点击js
    [_webView stringByEvaluatingJavaScriptFromString:@"function registerImageClickAction(){\
     var imgs=document.getElementsByTagName('img');\
     var length=imgs.length;\
     for(var i=0;i<length;i++){\
     img=imgs[i];\
     img.onclick=function(){\
     window.location.href='image-preview:'+this.src}\
     }\
     }"];
    [_webView stringByEvaluatingJavaScriptFromString:@"registerImageClickAction();"];
    
    
}


//  点击UIWebView图片的代理方法
//  在这个方法中捕获到图片的点击事件和被点击图片的url
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    
    //预览图片
    
    if ([request.URL.scheme isEqualToString:@"image-preview"]) {
        
        NSString* path = [request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];
        
        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        //path 就是被点击图片的url
     //   NSLog(@"%@",path);
        
//        MqWebPictureShowViewController *PicDetail = [[MqWebPictureShowViewController alloc] init];
//        PicDetail.array = _UrlArray;
//        [self.navigationController pushViewController:PicDetail animated:NO];
        
        for (int i = 0; i < _UrlArray.count; i++) {
            
            
           // NSLog(@"%@",_UrlArray[i]);
            
            if ([_UrlArray[i] isEqualToString:path]) {
                
                 [self showBigImage:path index:i];
                
            }
            
        }
        
        return NO;
        
    }
    
    return YES;
}


#pragma mark -
//显示大图片
-(void)showBigImage:(NSString *)imageName
              index:(NSInteger)index
{
    //创建灰色透明背景，使其背后内容不可操作
    
    UIScrollView *bgView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    NSInteger count = _UrlArray.count;
    bgView.contentSize = CGSizeMake(kScreenWidth * count, 0);
    bgView.pagingEnabled = YES;
    bgView.contentOffset = CGPointMake(kScreenWidth * index, 0);
    [bgView setBackgroundColor:[UIColor colorWithRed:0.3
                                               green:0.3
                                                blue:0.3
                                               alpha:0.7]];
    

    for (int i = 0; i < count; i++) {
        
        
        //创建边框视图
        UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0 + kScreenWidth * i, 0, BIG_IMG_WIDTH+16, BIG_IMG_HEIGHT+16)];
        //将图层的边框设置为圆脚
        borderView.layer.cornerRadius = 8;
        borderView.layer.masksToBounds = YES;
        //给图层添加一个有色边框
        borderView.layer.borderWidth = 8;
        borderView.layer.borderColor = [[UIColor colorWithRed:0.9
                                                        green:0.9
                                                         blue:0.9
                                                        alpha:0.7] CGColor];
        //[borderView setCenter:bgView.center];
        [borderView setCenter:CGPointMake(bgView.center.x + kScreenWidth * i, bgView.center.y)];
        [bgView addSubview:borderView];
        
        
        //创建关闭按钮
        UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [closeBtn setImage:[UIImage imageNamed:@"info-close"] forState:UIControlStateNormal];
        [closeBtn addTarget:self action:@selector(removeBigImage:) forControlEvents:UIControlEventTouchUpInside];
        [closeBtn setFrame:CGRectMake(borderView.frame.origin.x+borderView.frame.size.width-20*kWidthBase, borderView.frame.origin.y-6*kHeightBase, 26*kWidthBase, 27*kHeightBase)];
        [bgView addSubview:closeBtn];
        
        //创建显示图像视图
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(8*kWidthBase, 8*kHeightBase, BIG_IMG_WIDTH,BIG_IMG_HEIGHT)];
        [imgView sd_setImageWithURL:[NSURL URLWithString:_UrlArray[i]] placeholderImage:[UIImage imageNamed:@"infoplaceholder"]];
        [borderView addSubview:imgView];

        
        UILabel *numLabel = [[UILabel alloc] initWithFrame:CGRectMake(borderView.left, borderView.bottom + 10*kHeightBase, borderView.width, 50*kHeightBase)];
        numLabel.textAlignment = NSTextAlignmentCenter;
       // numLabel.backgroundColor = [UIColor redColor];
        numLabel.textColor = [UIColor whiteColor];
        numLabel.font = [UIFont systemFontOfSize:20];
        numLabel.text = [NSString stringWithFormat:@"%d / %ld",i + 1,(long)count];
        [bgView addSubview:numLabel];
        
        [self.view addSubview:bgView];
        
    }
    
}

//移除大图片
-(void)removeBigImage:(UIButton *)btn{
    [[btn superview] removeFromSuperview];
}


#pragma mark ---- tableView的代理方法
// 返回section的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_tagListArray.count != 0 && _authArray.count != 0) {
        
        return 4;
    } else if (_tagListArray.count == 0 && _authArray.count == 0)
    {
        return 2;
    } else
    return 3;
    
    
}

// 返回每个分区的行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    if (_tagListArray.count != 0 && _authArray.count != 0) {
        
        if (section == 0) {
            // 标签区
            return 1;
            
        } else if (section == 1){
            // 作者区
            return _authArray.count;
        } else if (section == 2) {
            // 推荐区:
            return _recommendListArray.count;
        } else
        // 评论区
        return _commentListArray.count;
        
        
    } else if (_tagListArray.count == 0 && _authArray.count == 0)
    {
        // 没有标签区和没有作者区
        
        if (section == 0) {
            
            return _recommendListArray.count;
            
        } else
        return _commentListArray.count;
        
        
    } else {
        
        // 存在3个区
        
        if (section == 0) {
            
            // 要么是标签,要么是作者
            return 1;
            
        }
        else if (section == 1) {
            
            return _recommendListArray.count;
        } else
        return _commentListArray.count;
        
    }
 
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_tagListArray.count != 0 && _authArray.count != 0) {
        
        if (indexPath.section == 0) {
            
            // 标签
            static NSString *identifier = @"tagCell";
            MqInfoTagTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                
                cell = [[MqInfoTagTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
            }
            cell.tagModelArray = _tagListArray;
           
            return cell;
            
            
        } else if (indexPath.section == 1) {
            
            // 作者信息
            static NSString *identifier = @"authCell";
            MqInfoAuthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                
                cell = [[MqInfoAuthTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                
            }
            MqAuthModel *model = _authArray[indexPath.row];
            cell.model = model;
            
            return cell;
            
            
        } else if (indexPath.section == 2) {
            
            // 相关文章
            static NSString *identifier = @"recommendedCell";
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                
                cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
            }
            
            MqInfoListModel *model = _recommendListArray[indexPath.row];
            cell.textLabel.text = model.title;
            
            return cell;
            
        } else {
            
            // 最新评论
            static NSString *identifier = @"commentCell";
            MqTInfoCommentableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                
                cell = [[MqTInfoCommentableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
            }
            
           MqCommentModel *model = _commentListArray[indexPath.row];
            cell.model = model;
            
            return cell;
            
        }
        
        
    } else if (_tagListArray.count == 0 && _authArray.count == 0) {
        
        // 说明只有推荐和评论
        if (indexPath.section == 0) {
            
            // 相关文章
            static NSString *identifier = @"recommendedCell";
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                
                cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
            }
            
            MqInfoListModel *model = _recommendListArray[indexPath.row];
            cell.textLabel.text = model.title;
            
            return cell;
            
            
        } else {
            
            
            // 最新评论
            static NSString *identifier = @"commentCell";
            MqTInfoCommentableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (cell == nil) {
                
                cell = [[MqTInfoCommentableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
            }
            
           MqCommentModel *model = _commentListArray[indexPath.row];
            cell.model = model;
            
            return cell;
            
        }
        
        
    } else {
        
        
        if (_tagListArray.count == 0) {
            
            if (indexPath.section == 0) {
                
                // 作者信息
                static NSString *identifier = @"authCell";
                MqInfoAuthTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    
                    cell = [[MqInfoAuthTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                    
                }
                MqAuthModel *model = _authArray[indexPath.row];
                cell.model = model;
                
                return cell;
                
                
            } else if (indexPath.section == 1) {
                
                // 相关文章
                static NSString *identifier = @"recommendedCell";
                
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    
                    cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }
                
                MqInfoListModel *model = _recommendListArray[indexPath.row];
                cell.textLabel.text = model.title;
                
                return cell;
                
                
            } else {
                
                // 最新评论
                static NSString *identifier = @"commentCell";
                MqTInfoCommentableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    
                    cell = [[MqTInfoCommentableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }
                
                MqCommentModel *model = _commentListArray[indexPath.row];
                cell.model = model;
                
                return cell;
                
                
            }
            
        } else {
            
            
            // 说明有标签,无作者
            if (indexPath.section == 0) {
                
                
                // 标签
                static NSString *identifier = @"tagCell";
                MqInfoTagTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    
                    cell = [[MqInfoTagTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }
                cell.tagModelArray = _tagListArray;
                
                return cell;
                
            } else if (indexPath.section == 1) {
                
                // 相关文章
                static NSString *identifier = @"recommendedCell";
                
                UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    
                    cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }
                
                MqInfoListModel *model = _recommendListArray[indexPath.row];
                cell.textLabel.text = model.title;
                
                return cell;
                
                
            } else {
                
                // 最新评论
                static NSString *identifier = @"commentCell";
                MqTInfoCommentableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
                if (cell == nil) {
                    
                    cell = [[MqTInfoCommentableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
                }
                
                MqCommentModel *model = _commentListArray[indexPath.row];

                cell.model = model;
                
                return cell;
                
            }

        }
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_tagListArray.count != 0 && _authArray.count != 0) {
        
        
        if (indexPath.section == 0) {
            
            return 100*kHeightBase;
            
        } else if (indexPath.section == 1) {
            
            return 180*kHeightBase;
        } else if (indexPath.section == 2) {
            
            return 60*kHeightBase;
        } else
        return 130*kHeightBase;
        
    } else if (_tagListArray.count == 0 && _authArray.count == 0) {
        
        
        if (indexPath.section == 0) {
            
            return 60*kHeightBase;
            
        } else
        return 130*kHeightBase;
        
    } else {
        
        if (_tagListArray.count == 0) {
            
            if (indexPath.section == 0) {
                
                return 180*kHeightBase;
                
            } else if (indexPath.section == 1) {
                
                return 60*kHeightBase;
            } else
            return 130*kHeightBase;
            
        } else {
            
            if (indexPath.section == 0) {
                
                return 100*kHeightBase;
                
            } else if (indexPath.section == 1) {
                
                return 60*kHeightBase;
            } else
            return 130*kHeightBase;
        }
        
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (_tagListArray.count != 0 && _authArray.count != 0) {
        
        
        if (section == 0) {
            
            return _sectionNameArray[0];
        } else if (section == 1) {
            return _sectionNameArray[1];
        } else if (section == 2) {
            return _sectionNameArray[2];
        } else
        return _sectionNameArray[3];
        
        
        
    } else if (_tagListArray.count == 0 && _authArray.count == 0)
    {
        
        if (section == 0) {
            
            return _sectionNameArray[2];
        } else
        return _sectionNameArray[3];
        
        
        
    } else {
        
        if (_tagListArray.count == 0) {
            
            if (section == 0) {
                
                return _sectionNameArray[1];
                
            }
            else if (section == 1) {
                
                return _sectionNameArray[2];
            } else
            return _sectionNameArray[3];
            
        } else {
            
            if (section == 0) {
                
                return _sectionNameArray[0];
                
            }
            else if (section == 1) {
                
                return _sectionNameArray[2];
            } else
            return _sectionNameArray[3];
            
        }
    }
    
    
    
    
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (_tagListArray.count != 0 && _authArray.count != 0) {
        
        if (indexPath.section == 0) {
            
 
        }
        
        else if (indexPath.section == 1) {
            
            // 作者
            MqInfoAuthDetailViewController *authdetailVC = [[MqInfoAuthDetailViewController alloc]init];
            
            MqAuthModel *model = _authArray[0];
            authdetailVC.authDetailURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getAuthorInfByType&type=authorColumnNewsList&columnid&columnid=%@",model.columnid];
            authdetailVC.name = model.name;
            authdetailVC.position = model.position;
            authdetailVC.authDescription = model.Description;
            authdetailVC.imageUrl = model.userPic;
            [self.navigationController pushViewController:authdetailVC animated:YES];
            
        } else if (indexPath.section == 2) {
            
            // 相关文章
            MqInfoWebViewController *webVCNEW = [[MqInfoWebViewController alloc] init];
            MqInfoListModel *model = _recommendListArray[indexPath.row];
            NSString *ids = model.topicDetailID;
            NSString *classID = model.classid;
            
            webVCNEW.idsURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=render&&classid=1&id=%@&userid=682480&version=1",ids];
            
            // 标签的网址
            webVCNEW.tagListURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getArticleTagOrTagListByType&type=tagList&id=%@",ids];
            
            // 作者信息的网址
            webVCNEW.authorInfoURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getAuthorInfByType&type=authorInfo&classid=%@&id=%@",classID,ids];
            
            // 相关文章的网址
            webVCNEW.recommendListURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=render&version=1&platform=1&classid=%@&showType=recommendList",classID];
            // 评论的网址
            webVCNEW.commentURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=comment&methodType=getArticleCommentV1&access_token=&classid=%@&id=%@",classID,ids];
            
            [self.navigationController pushViewController:webVCNEW animated:YES];
            
        } else {
            
            
//            NSLog(@"评论%ld",(long)indexPath.row);
            
        }
        
        
    } else if (_tagListArray.count == 0 && _authArray.count == 0) {
        
        if (indexPath.section == 0) {
            
            
            // 相关文章
            MqInfoWebViewController *webVCNEW = [[MqInfoWebViewController alloc] init];
            MqInfoListModel *model = _recommendListArray[indexPath.row];
            NSString *ids = model.topicDetailID;
            NSString *classID = model.classid;
            
            webVCNEW.idsURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=render&&classid=1&id=%@&userid=682480&version=1",ids];
            
            // 标签的网址
            webVCNEW.tagListURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getArticleTagOrTagListByType&type=tagList&id=%@",ids];
            
            // 作者信息的网址
            webVCNEW.authorInfoURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getAuthorInfByType&type=authorInfo&classid=%@&id=%@",classID,ids];
            
            // 相关文章的网址
            webVCNEW.recommendListURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=render&version=1&platform=1&classid=%@&showType=recommendList",classID];
            // 评论的网址
            webVCNEW.commentURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=comment&methodType=getArticleCommentV1&access_token=&classid=%@&id=%@",classID,ids];
            
            [self.navigationController pushViewController:webVCNEW animated:YES];
            
        } else {
            
//            NSLog(@"评论%ld",(long)indexPath.row);
        }
        
        
    }else {
        
        
        if (_tagListArray.count == 0) {
            
            // 无标签,有作者
            if (indexPath.section == 0) {
                
                // 作者
                MqInfoAuthDetailViewController *authdetailVC = [[MqInfoAuthDetailViewController alloc]init];
                MqAuthModel *model = _authArray[0];
                authdetailVC.authDetailURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getAuthorInfByType&type=authorColumnNewsList&columnid&columnid=%@",model.columnid];
                authdetailVC.name = model.name;
                authdetailVC.position = model.position;
                authdetailVC.authDescription = model.Description;
                authdetailVC.imageUrl = model.userPic;
                [self.navigationController pushViewController:authdetailVC animated:YES];

                
            } else if (indexPath.section == 1) {

                // 相关文章
                MqInfoWebViewController *webVCNEW = [[MqInfoWebViewController alloc] init];
                MqInfoListModel *model = _recommendListArray[indexPath.row];
                NSString *ids = model.topicDetailID;
                NSString *classID = model.classid;
                
                webVCNEW.idsURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=render&&classid=1&id=%@&userid=682480&version=1",ids];
                
                // 标签的网址
                webVCNEW.tagListURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getArticleTagOrTagListByType&type=tagList&id=%@",ids];
                
                // 作者信息的网址
                webVCNEW.authorInfoURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getAuthorInfByType&type=authorInfo&classid=%@&id=%@",classID,ids];
                
                // 相关文章的网址
                webVCNEW.recommendListURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=render&version=1&platform=1&classid=%@&showType=recommendList",classID];
                // 评论的网址
                webVCNEW.commentURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=comment&methodType=getArticleCommentV1&access_token=&classid=%@&id=%@",classID,ids];
                
                [self.navigationController pushViewController:webVCNEW animated:YES];

                
                
            } else {
                
//                NSLog(@"评论%ld",(long)indexPath.row);
                
            }
            
            
            
            
        }  else {
            // 无作者
            if (indexPath.section == 0) {
                
            } else if (indexPath.section == 1) {
                
                // 相关文章
                MqInfoWebViewController *webVCNEW = [[MqInfoWebViewController alloc] init];
                MqInfoListModel *model = _recommendListArray[indexPath.row];
                NSString *ids = model.topicDetailID;
                NSString *classID = model.classid;
                
                webVCNEW.idsURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=render&&classid=1&id=%@&userid=682480&version=1",ids];
                
                // 标签的网址
                webVCNEW.tagListURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getArticleTagOrTagListByType&type=tagList&id=%@",ids];
                
                // 作者信息的网址
                webVCNEW.authorInfoURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=getAuthorInfByType&type=authorInfo&classid=%@&id=%@",classID,ids];
                
                // 相关文章的网址
                webVCNEW.recommendListURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=render&version=1&platform=1&classid=%@&showType=recommendList",classID];
                // 评论的网址
                webVCNEW.commentURL = [NSString stringWithFormat:@"http://www.biketo.com/app.php?m=client&a=comment&methodType=getArticleCommentV1&access_token=&classid=%@&id=%@",classID,ids];
                
                [self.navigationController pushViewController:webVCNEW animated:YES];

                
            } else {
                
//                 NSLog(@"评论%ld",(long)indexPath.row);
            }
           
        }
        
    }
    
    
}




- (void)addNavBar
{
    
    _barView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 64 * kHeightBase)];
    _barView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:_barView];
    
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backButton.frame = CGRectMake(10 * kWidthBase, 30 * kHeightBase, 20 * kWidthBase, 20 * kHeightBase);
    [backButton setBackgroundImage:[UIImage imageNamed:@"info-back"] forState:(UIControlStateNormal)];
    [backButton addTarget:self action:@selector(backAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [_barView addSubview:backButton];
    
    //  收藏
    UIButton *collectionButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    
    collectionButton.frame = CGRectMake(kScreenWidth - 60, backButton.top, backButton.width, backButton.height);
    [collectionButton setBackgroundImage:[UIImage imageNamed:@"btn_collection_new@2x"] forState:(UIControlStateNormal)];
    [collectionButton addTarget:self action:@selector(collectionArticle) forControlEvents:(UIControlEventTouchUpInside)];
    [_barView addSubview:collectionButton];
    
    
}

- (void)backAction:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
